import type { Recordable, RouteRecordStringComponent } from '@croco/framework/types';

import { LOGIN_PATH } from '@croco/framework/constants';
import { resetAllStores, useUserStore } from '@croco/framework/stores';

import { service } from '#/api/request';
import { router } from '#/router';

/**
 * 获取用户信息
 */
export async function getUserDetails() {
    const userStore = useUserStore();
    return await service.get(`/profile/details?username=${userStore.loginUser?.username}`);
}

/**
 * 获取用户所有菜单
 */
export async function getUserMenus() {
    const userStore = useUserStore();
    return await service.get(`/profile/menus?username=${userStore.loginUser?.username}`).then(({ data }): RouteRecordStringComponent[] => data);
}

/**
 * 获取用户权限码
 */
export async function getUserPermissions() {
    const userStore = useUserStore();
    return await service.get<Recordable<any>>(`/profile/permissions?username=${userStore.loginUser?.username}`).then(({ data }) => data);
}

/**
 * 刷新accessToken
 */
export async function refreshToken() {
    const userStore = useUserStore();
    return await service.post('/refreshToken', { username: userStore.loginUser?.username }).then(({ data }) => data);
}

/**
 * 获取字典数据
 */
export function getDictTrim(type: string | string[]) {
    return service.get('/dictionary', { type }).then(({ data }) => {
        if (Array.isArray(type)) {
            const values = [];
            for (const item of type) {
                values.push(data[item]);
            }
            return values;
        } else {
            return [data[type]];
        }
    });
}

/**
 * 退出登录
 */
export async function logout() {
    const userStore = useUserStore();
    await service
        .post(`/profile/logout`, {
            username: userStore.loginUser?.username,
            withCredentials: true,
        })
        .then(async () => {
            await clearStores(false);
        });
}

/**
 * 清除缓存，并跳转回登录页
 * @param redirect 是否跳转回当前页面
 */
export async function clearStores(redirect: boolean = true) {
    const userStore = useUserStore();
    resetAllStores();
    userStore.setLoginExpired(false);
    // 回登录页带上当前路由地址
    await router.push({
        path: LOGIN_PATH,
        query: redirect ? { redirect: encodeURIComponent(router.currentRoute.value.fullPath) } : {},
    });
}

export function getRoleOptions(name: string = '') {
    return service.get('/system/role/options', { name });
}

export function getRoleDetails(id: number | number[] | undefined) {
    return service.get('/system/role/details', { id });
}

export function getDeptTree() {
    return service.get('/system/dept/tree', {});
}

export function getMenuTree(type?: string) {
    return service.get('/system/menu/tree', { type });
}

export function getMenuDetails(id: number | number[] | undefined) {
    return service.get('/system/menu/details', { id });
}

export function getMenuModule() {
    return service.get('/system/menu/module');
}
